<?php

namespace App\Http\Controllers\OperationManagement;

use Illuminate\Http\Request;
use App\Http\Controllers\Controller;
use App\Models\OperationManagement\SanitationSite;
use App\Models\OperationManagement\SanitationCategory;
use App\Models\OperationManagement\SanitationSiteFile;
use App\Models\SystemManagement\Organization;
use App\Models\SystemManagement\Employee;
use Illuminate\Database\QueryException;
use App\Http\Requests\OperationManagement\SanitationSiteRequest;
use Grimzy\LaravelMysqlSpatial\Types\Point;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Storage;

/**
 * @group 基础信息管理->环卫->基础设施
 *
 * 采用 restful api
 *
 * Body Parameters 表示请求的所需要的参数
 *
 * Query Parameters 表示返回参数的名称
 */

class SanitationSiteController extends Controller
{
    /**
     * 基础设施信息查看列表
     *
     * @bodyParam name string 站点名称
     * @bodyParam category_id int 站点类型 外键 站点类型表
     * @bodyParam location string 经纬度-点 115.24556,25.14551
     *
     * @queryParam name string 站点名称
     * @queryParam number string 编号
     * @queryParam category_id int 站点类型 外键 站点类型表
     * @queryParam category->name string 站点类型
     * @queryParam address string 地址
     * @queryParam location string 经纬度-点 115.24556,25.14551
     * @queryParam handle int 日处理量
     * @queryParam property_company string 产权单位
     * @queryParam operate_company string 运营单位
     * @queryParam employees->name string 负责人 外键 员工表
     * @queryParam phone string 电话
     * @queryParam status int 状态
     * @queryParam rfid int RFID绑定
     * @queryParam files->file->local_url string 附件url地址
     *
     * @return \Illuminate\Http\Response
     */
    public function index(Request $request)
    {
        $sanitationSite = new SanitationSite;
        $data = $sanitationSite->getList($request);
        return response()->json(encodeMsg($data,200));
    }

    /**
     * 添加基础设施信息
     *
     * @bodyParam name string 站点名称
     * @bodyParam number string 编号
     * @bodyParam category_id int 站点类型 外键 站点类型表
     * @bodyParam address string 地址
     * @bodyParam location string 经纬度-点 115.24556,25.14551
     * @bodyParam handle int 日处理量
     * @bodyParam property_company string 产权单位
     * @bodyParam operate_company string 运营单位
     * @bodyParam principal_id int 负责人 外键 员工表
     * @bodyParam phone string 电话
     * @bodyParam status int 状态
     * @bodyParam rfid int RFID绑定
     * @bodyParam sanitation_site_ids string 站点附件ids:1,2
     *
     * @queryParam name string 站点名称
     * @queryParam number string 编号
     * @queryParam category_id int 站点类型 外键 站点类型表
     * @queryParam category->name string 站点类型
     * @queryParam address string 地址
     * @queryParam location string 经纬度-点 115.24556,25.14551
     * @queryParam handle int 日处理量
     * @queryParam property_company string 产权单位
     * @queryParam operate_company string 运营单位
     * @queryParam employees->name string 负责人 外键 员工表
     * @queryParam phone string 电话
     * @queryParam status int 状态
     * @queryParam rfid int RFID绑定
     * @queryParam sanitation_site_ids string 站点附件ids:1,2
     *
     * @return \Illuminate\Http\Response
     */
    public function store(SanitationSiteRequest $request)
    {
        DB::beginTransaction();
        try {
            $data = $request->all();
            // $data['location'] = \DB::raw("GeomFromText('Point({$request->input('location')})')");
            $location = $request->input('location','');
            if(!empty($location)){
                $data['location'] = Point::fromString($location);
            }
            $number = SanitationSite::orderBy('number','desc')->value('number');
            if(is_null($number)){
                $data['number'] = 1;
            }else{
                $data['number'] = seriesNum($number);
            }
            $data = SanitationSite::create($data);
            if($request->has('sanitation_site_ids')){
                $file_data = [];
                $fileArr = explode(',',$request->get('sanitation_site_ids'));
                foreach ($fileArr as $k=>$value){
                    $tmp = [];
                    $tmp['file_id'] = $value;
                    $tmp['sanitation_site_id'] = $data->id;
                    array_push($file_data,$tmp);
                }
                try{
                    SanitationSiteFile::insert($file_data);
                }catch (\Exception $e){
                    DB::rollBack();
                    return response()->json(encodeMsg(["message" => "请先确认图片是否已经添加或者图片id是否重复".$e->getMessage()],404), 404);
                }
            }
            DB::commit();
            return response()->json(encodeMsg($data,201));
        } catch (QueryException $e) {
            DB::rollBack();
            // dd($e);
            return response()->json(encodeMsg(['message' => '基础设施添加失败!'],400));
        }
    }

    /**
     * 查看基础设施信息
     *
     * @bodyParam id int required 站点ID
     *
     * @queryParam name string 站点名称
     * @queryParam number string 编号
     * @queryParam category_id int 站点类型 外键 站点类型表
     * @queryParam category->name string 站点类型
     * @queryParam address string 地址
     * @queryParam location string 经纬度-点 115.24556,25.14551
     * @queryParam handle int 日处理量
     * @queryParam property_company string 产权单位
     * @queryParam operate_company string 运营单位
     * @queryParam principal_id int 负责人 外键 员工表
     * @queryParam phone string 电话
     * @queryParam status int 状态
     * @queryParam rfid int RFID绑定
     * @queryParam files->file->local_url string 附件url地址
     *
     * @return \Illuminate\Http\Response
     */
    public function show($id)
    {
        $data = SanitationSite::with(['category','employees','files'])->find($id);
        if($data == []) {
            return response()->json(encodeMsg(["message" => "没有该基础设施信息!"], 404));
        } else {
            return response()->json(encodeMsg($data,200));
        }
    }

    /**
     * 修改基础设施信息
     *
     * @bodyParam name string 站点名称
     * @bodyParam number string 编号
     * @bodyParam category_id int 站点类型 外键 站点类型表
     * @bodyParam address string 地址
     * @bodyParam location string 经纬度-点 115.24556,25.14551
     * @bodyParam handle int 日处理量
     * @bodyParam property_company string 产权单位
     * @bodyParam operate_company string 运营单位
     * @bodyParam employees->name string 负责人 外键 员工表
     * @bodyParam phone string 电话
     * @bodyParam status int 状态
     * @bodyParam rfid int RFID绑定
     * @bodyParam sanitation_site_ids string 站点附件ids:1,2
     *
     * @queryParam name string 站点名称
     * @queryParam number string 编号
     * @queryParam category_id int 站点类型 外键 站点类型表
     * @queryParam category->name string 站点类型
     * @queryParam address string 地址
     * @queryParam location string 经纬度-点 115.24556,25.14551
     * @queryParam handle int 日处理量
     * @queryParam property_company string 产权单位
     * @queryParam operate_company string 运营单位
     * @queryParam employees->name string 负责人 外键 员工表
     * @queryParam phone string 电话
     * @queryParam status int 状态
     * @queryParam rfid int RFID绑定
     * @queryParam sanitation_site_ids string 站点附件ids:1,2
     *
     * @return \Illuminate\Http\Response
     */
    public function update(SanitationSiteRequest $request, $id)
    {
        $sanitationSite = SanitationSite::find($id);
        if($sanitationSite == []) {
            return response()->json(encodeMsg(["message" => "没有该站点信息!"], 404));
        }
        DB::beginTransaction();
        try {
            $data = $request->all();
            $location = $request->input('location','');
            if(!empty($location)){
                $data['location'] = Point::fromString($location);
            }
            if($request->has('sanitation_site_ids')){
                $origin_files = SanitationSiteFile::where('sanitation_site_id',$id)->get()->toArray();//图片原来的id号是好多 取出
                $origin_file_ids = array();//这个数组用于报错以前的所有file的id号
                if($origin_files != []){
                    foreach ($origin_files as $v){
                        array_push($origin_file_ids,$v['id']);
                    }
                }
                $file_data = [];
                $fileArr = explode(',',$request->get('sanitation_site_ids'));
                foreach ($fileArr as $k=>$value){
                    $tmp = [];
                    $tmp['file_id'] = $value;
                    $tmp['sanitation_site_id'] = $id;
                    array_push($file_data,$tmp);
                }
                try{
                    SanitationSiteFile::whereIn('id',$origin_file_ids)->delete();
                    SanitationSiteFile::insert($file_data);
                }catch (\Exception $e){
                    DB::rollBack();
                    return response()->json(encodeMsg(["message" => "请先确认图片是否已经添加或者图片id是否重复".$e->getMessage()],404), 404);
                }
            }
            $sanitationSite->update($data);
            DB::commit();
            return response()->json(encodeMsg($sanitationSite,200));
        } catch (QueryException $e) {
            DB::rollBack();
            // dd($e);
            return response()->json(encodeMsg(['message' => '基础设施修改失败!'],400));
        }
    }

    /**
     * 删除基础设施
     *
     *
     * @bodyParam id int required  站点ID
     * @response 204 {
     *   "message": "基础设施删除成功"
     * }
     *
     *
     * @response 404 {
     *  "message": "没有该基础设施信息"
     * }
     *
     * @return \Illuminate\Http\Response
     */
    public function destroy($id)
    {
        $sanitationSite = SanitationSite::find($id);
        if($sanitationSite == []) {
            return response()->json(encodeMsg(["message" => "没有该基础设施信息!"], 404));
        }
        if($sanitationSite->delete()) {
            return response()->json(encodeMsg(["message" => "基础设施删除成功!"], 204));
        } else {
            return response()->json(encodeMsg(["message" => "基础设施删除失败"], 400));
        }
    }

    /**
     * 批量删除基础设施
     *
     * @bodyParam  ids int required  id集合字符串[格式：ids=1,2,3]
     * @response 204 {
     *   "message": "基础设施删除成功"
     * }
     *
     *
     */
    public function delete($ids)
    {
        $listId = explode(',', $ids);
        SanitationSite::whereIn('id',$listId)->delete();
        return response()->json(encodeMsg(["message" => "基础设施删除成功!"], 204));
    }

    /**
     * 基础设施信息导入 excel
     *
     * @queryParam name string 站点名称
     * @queryParam number string 编号
     * @queryParam category_id int 站点类型 外键 站点类型表
     * @queryParam category->name string 站点类型
     * @queryParam address string 地址
     * @queryParam location string 经纬度-点 115.24556,25.14551
     * @queryParam handle int 日处理量
     * @queryParam property_company string 产权单位
     * @queryParam operate_company string 运营单位
     * @queryParam employees->name string 负责人 外键 员工表
     * @queryParam phone string 电话
     * @queryParam status int 状态
     * @queryParam rfid int RFID绑定
     *
     * @return \Illuminate\Http\Response
     */
    public function import(Request $request)
    {
        $data = excelImport($request);
        $sanitationSite = [];
        if(!empty($data)){
            foreach ($data as $k => $v) {
                unset($v[0]);
                foreach ($v as $key => $row) {
                    DB::beginTransaction();
                    try {
                        $sanitationSite[$k][$key]['name'] = $row[0];
                        //站点类型
                        $id = SanitationCategory::where('name',$row[1])->first('id');
                        if (!empty($id)) {
                            $sanitationSite[$k][$key]['category_id'] = $id->id;
                        } else if(!empty($row[1])) {
                            $info = SanitationCategory::create($row[1]);
                            $sanitationSite[$k][$key]['category_id'] = $info->id;
                        }

                        $sanitationSite[$k][$key]['address'] = $row[2];//地址
                        //经纬度
                        if (!empty($row[3])) {
                            $sanitationSite[$k][$key]['location'] = Point::fromString($row[3]);
                        }
                        //所属公司
                        $organization_id = Organization::where('name',$row[4])->first('id');
                        if (!empty($organization_id)) {
                            $sanitationSite[$k][$key]['organization_id'] = $organization_id->id;
                        } else if(!empty($row[4])) {
                            $info = Organization::create($row[4]);
                            $sanitationSite[$k][$key]['organization_id'] = $info->id;
                        }
                        //负责人
                        $principal_id = Employee::where('name',$row[5])->first('id');
                        if (!empty($principal_id)) {
                            $sanitationSite[$k][$key]['principal_id'] = $principal_id->id;
                        } else if(!empty($row[5])) {
                            $employee['name'] = $row[5];
                            $info = Employee::addData($employee);
                            $sanitationSite[$k][$key]['principal_id'] = $info->id;
                        }
                        $sanitationSite[$k][$key]['phone'] = $row[6];//电话
                        $sanitationSite[$k][$key]['number'] = $row[7];//日处理量
                        $sanitationSite[$k][$key]['run_time'] = $row[8];//运营时间
                        $sanitationSite[$k][$key]['end_time'] = $row[9];//停运时间
                        $data = $sanitationSite[$k][$key];
                        $res = SanitationSite::where(function($query) use ($data){
                            if(!empty($data['location'])){
                                $query->distance('location',$data['location'],10);
                            }
                            unset($data['location']);
                            $query->where($data);
                        })->first();
                        if (empty($res)) {
                            SanitationSite::create($sanitationSite[$k][$key]);
                        }
                        DB::commit();
                    } catch (QueryException $e) {
                        DB::rollBack();
                        // dd($e);
                        return response()->json(encodeMsg(['message' => '导入失败!'],400));
                    }
                }
                unset($sanitationSite[$k][$key]);
            }
            unset($sanitationSite[$k]);
        }
        if(Storage::disk('public')->exists('uploads/'.$request->file('file')->getClientOriginalName())) {
            return response()->json(encodeMsg(['message' => '文件已上传!'],200));
        }
    }

}
